package com.gaotu.ci.news;

import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toMap;


public class BadCollection {
    @Autowired
    private NewsRepository newsRepository;

    public Map<Long, String> getNewsTitle(List<News> news){
        Map<Long, News> newsMap = news.stream()
                .collect(toMap(News::getId, n -> n));

        Map<Long, String> result = new HashMap<>();

        for (Long id : newsMap.keySet()){
            News n = newsMap.get(id);
            result.put(id, n.getTitle());
        }

        return result;
    }

    public News getById(String idStr){
        long id = Long.parseLong(idStr);
        return getById(id);
    }

    public News getById(Long id){
        List<Long> ids = Arrays.asList(id);
        List<News> newsList = this.newsRepository.getByIdIn(ids);
        if (newsList.size() == 1){
            return newsList.get(0);
        }
        return null;
    }

    public News getNewsById(Long newsId){
        Optional<News> newsOptional = this.newsRepository.findById(newsId);
        return newsOptional.orElse(createEmptyNews());
    }


    private News createEmptyNews() {
        return News.apply("未知咨询", "请检查后在访问");
    }


    public List<String> getTitleFrom1(List<News> newsList){
        List<String> titles = new ArrayList<>();
        for (News news : newsList){
            titles.add(news.getTitle());
        }
        return titles;
    }

    public List<String> getTitleFrom2(List<News> newsList){
        return newsList.stream()
                .map(n -> n.getTitle())
                .collect(Collectors.toList());
    }

}
